const membersModel = require('../model/membersModel')
const members = {
  // 查找的 
  getMember(req, res) {
    let map = {$regex:req.query.username}
    membersModel.find({username:map}).then((rs) => {
      if (rs) {
        res.send({
          code: 0,
          msg: 'ok',
          data: rs
        })
      } else {
        res.send({
          code: 1,
          msg: 'error',
          data: []
        })
      }
    })
  },
  getMembers(req, res) {
    membersModel.find({}).then((rs) => {
      if (rs) {
        res.send({
          code: 0,
          msg: 'ok',
          data: rs
        })
      } else {
        res.send({
          code: 1,
          msg: 'error',
          data: []
        })
      }
    })
  },
  addMember(req, res) {
    let data = req.body
    membersModel
      .insertMany([data])
      .then((rs) => {
        if (rs) {
          res.send({
            code: 0,
            msg: '添加成功',
            data: rs
          })
        } else {
          res.send({
            code: 1,
            msg: '添加失败',
            data: []
          })
        }
      })
      .catch((err) => {
        console.log(err)
        res.send({
          code: 1,
          msg: err.writeErrors[0].err.errmsg,
          data: []
        })
      })
  },
  deleteMembers(req, res) {
    let phone = req.params.phone
    membersModel.deleteOne({ phone }).then((rs) => {
      console.log(rs)
      if (rs.deletedCount === 1) {
        res.send({
          code: 0,
          msg: '删除成功',
          data: rs
        })
      } else {
        res.send({
          code: 1,
          msg: '删除失败',
          data: []
        })
      }
    })
  },
  updateMember(req, res) {
    let phone = req.body.phone
    let data = req.body
    membersModel
      .updateOne({ phone }, { $set: data })
      .then((rs) => {
        console.log(rs)
        if (rs.modifiedCount > 0) {
          res.send({
            code: 0,
            msg: '修改成功',
            // 返回 修改后的data
            data
          })
        } else {
          res.send({
            code: 1,
            msg: '修改失败',
            data: []
          })
        }
      })
      .catch((err) => {
        console.log(err)
        res.send({
          code: 1,
          msg: err.writeErrors[0].err.errmsg,
          data: []
        })
      })
    // res.send('修改用户数据测试')
  }
}
module.exports = members
